package de.slothsoft.bookmaker.parse;

import java.util.ArrayList;
import java.util.List;

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.apache.commons.lang3.StringEscapeUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

public final class XPathUtil {

    private static final XPathFactory FACTORY = XPathFactory.newInstance();
    private static final XPath PATH = FACTORY.newXPath();

    public static List<String> findAttributes(Document document, String node, String attribute)
            throws XPathExpressionException {
        NodeList nodeList = (NodeList) PATH.evaluate(node + "[@" + attribute + "]", document, XPathConstants.NODESET);
        int length = nodeList.getLength();
        List<String> result = new ArrayList<>(length);
        for (int i = 0; i < length; i++) {
            String value = StringEscapeUtils.unescapeHtml4(((Element) nodeList.item(i)).getAttribute(attribute));
            if (!result.contains(value)) {
                result.add(value);
            }
        }
        return result;
    }

    public static String findAttribute(Document document, String node, String attribute)
            throws XPathExpressionException {
        NodeList nodeList = (NodeList) PATH.evaluate(node + "[@" + attribute + "]", document, XPathConstants.NODESET);
        for (int i = 0; i < nodeList.getLength();) {
            return StringEscapeUtils.unescapeHtml4(((Element) nodeList.item(i)).getAttribute(attribute));
        }
        return null;
    }

    private XPathUtil() {
        // weee!
    }

}
